package net.wanho.shop.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.aliyun.oss.OSSClient;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import net.wanho.shop.common.UserConstant;
import net.wanho.shop.dto.PasswordDTO;
import net.wanho.shop.dto.UserDTO;
import net.wanho.shop.exception.UserExistsException;
import net.wanho.shop.mapper.UserMapper;
import net.wanho.shop.po.User;
import net.wanho.shop.service.UserService;
import net.wanho.shop.vo.PageVo;
import net.wanho.shop.vo.SearchByIdVo;
import net.wanho.shop.vo.UserVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 猛虎王
 * @since 2024-12-24
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    //    private final OSSClient ossClient;
    @Resource
    private OSSClient ossClient;
    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    /**
     * 用户表分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param user
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public PageVo findPage(int pageNum, int pageSize, User user) {
        if (ObjectUtil.isNull(user)) {
            user = new User();
        }

        // 分页
        PageHelper.startPage(pageNum, pageSize);
        List<UserVo> userList = userMapper.select(user);
        PageInfo<UserVo> pageInfo = new PageInfo<>(userList);

//        Map<String, Object> map = new HashMap<>();
//        map.put("total", pageInfo.getTotal());
//        map.put("pageNum", pageInfo.getPageNum());
//        map.put("users", pageInfo.getList());
//        PageVo pageVo = new PageVo();
        PageVo pageVo = new PageVo(pageInfo.getTotal(), pageInfo.getPageNum());
//        pageVo.setTotal(pageInfo.getTotal());
//        pageVo.setPageNum(pageInfo.getPageNum());
        pageVo.put("users", pageInfo.getList());

        return pageVo;
    }

    /**
     * 根据主键查询用户表
     *
     * @param id
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
//    @Async // 表示该方法是异步方法
    public SearchByIdVo findById(Serializable id) {
//        System.out.println("UserServiceImpl.findById--------------线程名：" + Thread.currentThread().getName());
        return userMapper.findBySearchId(id);
    }

    /**
     * 用户表新增
     *
     * @param user
     */
    @Override
    public void add(User user) {
        User loginUser = userMapper.selectByUserName(user.getUsername());
        // 判断用户名是否重复
        if (loginUser != null) {
            throw new UserExistsException("用户名重复");
        }
        // 判断号码是否重复
        User userMobile = userMapper.selectByMobile(user.getMobile());
        if (userMobile != null) {
            throw new UserExistsException("号码重复");
        }

        user.setPassword(SecureUtil.md5(user.getPassword()));
        user.setCreateTime(LocalDateTime.now());
        user.setRoleId(UserConstant.ROLE_DEFAULT);
        user.setMgState(UserConstant.STATE_ENABLE);


        userMapper.insert(user);
    }

    /**
     * 修改用户表
     *
     * @param user
     */
    @Override
    public void modify(User user) {
        userMapper.update(user);
    }

    /**
     * 根据主键删除用户表
     *
     * @param id
     */
    @Override
    public void removeById(Serializable id) {
        if (((String) id).contains(",")) {
            userMapper.deleteByIds(((String) id).split(","));
        } else {
            userMapper.deleteById(id);
        }
    }

    @Override
    public void modifyState(Integer id, Integer state) {
        userMapper.updateState(id, state);
    }

    @Override
    public void modifyUser(Integer id, User user) {
        // 判断用户是否存在
        User loginUser = userMapper.selectById(id);
        if (loginUser == null) {
            throw new UserExistsException("用户不存在");
        }
        // 创建对象 并赋值
        user.setId(id);
        // 修改
        userMapper.update(user);
    }

    @Override
    public void modifyRole(Integer id, Integer roleId) {
        userMapper.updateRole(id, roleId);
    }

    @Override
    public void modifyPassword(PasswordDTO passwordDTO) {
        User user = userMapper.selectById(passwordDTO.getId());
        if (user == null)
            throw new UserExistsException("用户不存在");
        if (!user.getPassword().equals(SecureUtil.md5(passwordDTO.getOldPassword())))
            throw new UserExistsException("旧密码错误");
        if (!passwordDTO.getPassword().equals(passwordDTO.getRepeatPassword()))
            throw new UserExistsException("新密码与确认密码不一致");

        String newPassword = SecureUtil.md5(passwordDTO.getPassword());
        System.out.println(newPassword);

        userMapper.updatePassword(passwordDTO.getId(), newPassword);
    }

    @Override
    public void modifyUserInfo(UserDTO useDTO) {
        User user = userMapper.selectById(useDTO.getId());
        User newUser = new User();
        newUser.setId(useDTO.getId());
        newUser.setUsername(useDTO.getUsername());
        newUser.setMobile(useDTO.getMobile());
        newUser.setEmail(useDTO.getEmail());
        newUser.setAvatar(user.getAvatar());
        newUser.setPassword(user.getPassword());
        newUser.setRoleId(user.getRoleId());
        newUser.setMgState(user.getMgState());
        newUser.setCreateTime(user.getCreateTime());
        userMapper.update(newUser);
    }

    @Override
    @SneakyThrows
    public String modifyUserHead(Integer id, MultipartFile file) {
        String dir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String filename = file.getOriginalFilename();
        User user = userMapper.selectById(id);
        String objectName = dir + "/" + UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));

        ossClient.putObject(bucket, objectName, file.getInputStream());

        String url = "https://" + bucket + "." + endpoint + "/" + objectName;
        user.setAvatar(url);
        userMapper.update(user);

        return url;
//        return objectName;
    }
}
